﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using WebApp.Models;
using WebApp.BLL.Manage;
using WebApp.BLL;
using WebApp.ViewModels;
using WebApp.Common;
using WebApp.Web.Core.Auth;
using Newtonsoft.Json.Linq;
using WebApp.ViewModels.Manage;
using WebApp.Common.Caching;
using WebApp.Web.Core;

namespace kzjd.rycp.WebApp.Areas.Manage.Controllers
{
    public class SettingController : Controller
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger("WebApp.Log");

        #region List

        // GET: Manage/User

        [AuthorizeFilter("Manage.Environment")]
        public ActionResult List()
        {
            var list = new S_environmentService().List();

            ViewBag.DataJson = Newtonsoft.Json.JsonConvert.SerializeObject(list);

            return View();
        }

        #endregion

        #region Save

        [AuthorizeFilter("Manage.Environment")]
        [ValidateInput(false)]
        public JsonResult Save(string json)
        {
            try
            {
                //if (!"admin".Equals(SessionManage.User.Username, StringComparison.OrdinalIgnoreCase))
                //{
                //    return Json(new AjaxResult(AjaxResult.RESULT_ERROR, CSMSLang.Get("message_failure")));
                //}

                var service = new S_environmentService();

                EnvironmentEditModel model = Newtonsoft.Json.JsonConvert.DeserializeObject<EnvironmentEditModel>(json);

                var list = new List<S_environment>();
                foreach (var row in model.Rows)
                {
                    var item = new S_environment
                    {
                       // Custcode = "-"
                    };

                    if (row.Id > 0) item = service.Find(row.Id);

                    //将Json数据赋值给Model对象
                    row.SetModelData<S_environment>(item);

                    list.Add(item);
                }

                service.Save(list, model.DeletedRows);

                //清缓存
                service.ClearCache();

                return Json(new AjaxResult(AjaxResult.RESULT_OK, CSMSLang.Get("message_save_success")));
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return Json(new AjaxResult(AjaxResult.RESULT_ERROR, ex.Message));
            }
        }

        #endregion

        #region 清除所有缓存

        [AuthorizeFilter("Manage.Environment")]
        public ActionResult ClearCache()
        {
            new MemoryCacheManager().Clear();

            return Json("缓存已清除！", JsonRequestBehavior.AllowGet);
        }

        #endregion
    }
}
